package com.lcx.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Activate(group = {CommonConstants.PROVIDER})
public class TPMonitorFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        Map<String, List<Long>> map = new ConcurrentHashMap<>();
        long  startTime  = System.currentTimeMillis();
        try {
            // 执行方法
            Result result = invoker.invoke(invocation);
            Long time = System.currentTimeMillis()-startTime;
            String methodName = invocation.getMethodName();
            List<Long> longs = map.get(methodName);
            if (longs != null){
                longs.add(time);
                map.put(methodName,longs);
            }else{
                List<Long> list = new ArrayList<>();
                list.add(time);
                map.put(methodName,list);
            }
            return  result;
        } finally {
            Set<Map.Entry<String, List<Long>>> entries = map.entrySet();
            for (Map.Entry<String, List<Long>> entry : entries) {
                String key = entry.getKey();
                List<Long> value = entry.getValue();
                int size = value.size();
                int tp90 = size * 90 / 100;
                int tp99 = size * 99 / 100;
                Collections.sort(value, Collections.reverseOrder());
                Long v = value.get(tp90);
                Long v2 = value.get(tp99);
                try {
                    Thread.sleep(1000);
                    System.out.println("TP90-"+key+":"+v+"毫秒,,,"+"TP99-"+key+":"+v2+"毫秒!!!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
